package com.yz.sharkim.util;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.springframework.util.Base64Utils;
import org.springframework.util.DigestUtils;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.Charset;

/**
 * @author yangzheng
 * @version 1.0
 * @date 2019/11/16
 */
@Slf4j
public abstract class AESUtils {

    private static final Charset UTF_8 = CharsetUtil.UTF_8;

    private static final String KEY_ALGORITHM = "AES";
    
    private static final String DEFAULT_CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";

    private static final byte[] S_KEY = DigestUtils.md5Digest("SHARK_IM".getBytes(UTF_8));

    /**
     * 编码
     * @param src
     * @return
     */
    public static String defaultEncrypt(String src) {
        return encrypt(src, S_KEY);
    }

    /**
     * 解码
     * @param src
     * @return
     */
    public static String defaultDecrypt(String src) {
        return decrypt(src, S_KEY);
    }

    public static String encrypt(String sSrc, byte[] raw) {
        try {
            val skeySpec = new SecretKeySpec(raw, KEY_ALGORITHM );
            val cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
            byte[] encrypted = cipher.doFinal(sSrc.getBytes(UTF_8));

            return Base64Utils.encodeToString(encrypted);
        } catch (Exception e) {
            log.error("AES encrypt error! {}", e.getMessage(), e);
        }
        return null;
    }


    public static String decrypt(String sSrc, byte[]  raw) {
        try {
            SecretKeySpec skeySpec = new SecretKeySpec(raw, KEY_ALGORITHM );
            Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, skeySpec);
            //base64解密
            byte[] encrypted1 = Base64Utils.decodeFromString(sSrc);
            byte[] original = cipher.doFinal(encrypted1);
            return new String(original,UTF_8);
        } catch (Exception e) {
            log.error("AES encrypt error! {}", e.getMessage(), e);
            return null;
        }
    }

}
